package org.coderfun.fieldmeta.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.coderfun.common.exception.ErrorCodeEnum;
import org.coderfun.fieldmeta.auth.AuthService;
import org.coderfun.member.core.SimpleMember;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import klg.common.model.JsonData;
import klg.common.utils.JacksonUtil;

public class AuthFilter implements Filter{
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthFilter.class);

    /**
     * 保存不拦截的url
     */
    private static List<String> passUrls = new ArrayList<>();

    /**
     * 上下文
     */
    private String ctxPath = null;

    /**
     * 重定向url
     */
    private static String redirectUrl = "";


    /**
     * 过滤器初始化方法
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        // 获取web.xml中的初始化参数
        String ignoreURL = filterConfig.getInitParameter("passURL");
        redirectUrl = filterConfig.getInitParameter("redirectURL");
        // 保存不拦截的url
        String[] ignoreURLArray = ignoreURL.split(",");
        for (String url : ignoreURLArray) {
            passUrls.add(url.trim());
        }
        ctxPath = filterConfig.getServletContext().getContextPath();
        System.out.println("ctx = " + ctxPath);
        LOGGER.info("不拦截的URL包括:");
        for (String url : passUrls) {
            LOGGER.info(url);
        }
    }


    /**
     * 过滤器方法
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 请求的url
        String url = request.getRequestURI();
        // 相对路径
        String subUrl = url.substring(ctxPath.length() + 1);

        for (String urlStr : passUrls) {
            // 如果匹配, 则放行
            if (subUrl.indexOf(urlStr) > -1) {
                filterChain.doFilter(request, response);
                return;
            }
        }

        // 获得session
        HttpSession session = request.getSession();
        // 从session中获取SessionKey对应值,若值不存在,则重定向到redirectUrl
		SimpleMember simpleMember = (SimpleMember) session.getAttribute(AuthService.MEMBER_ATTRIBUTE_NAME);
		if(null != simpleMember){
			filterChain.doFilter(request, response);
		}else{
			String requestType = request.getHeader("X-Requested-With");
			//ajax 请求
			if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
	        	//超时请求头
	            response.setHeader("sessionStatus", "timeout");
	            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
	            
	        	response.setCharacterEncoding("UTF-8");
	            response.setContentType("application/json");
	            JsonData jsonData = JsonData.error(ErrorCodeEnum.UNAUTHENTICATED.getCode(), 
	            		ErrorCodeEnum.UNAUTHENTICATED.getMessageFormat());
	            response.getWriter().write(JacksonUtil.toJSONString(jsonData));
				return;
			} else {
				response.sendRedirect(request.getContextPath() + redirectUrl);
				return;
			}
		}
    }


    @Override
    public void destroy() {

    }
}
